<link rel="stylesheet" href="/assets/assets(home)/plugin/ckplayer/css/ckplayer.css">
<link rel="stylesheet" href="/assets/assets(home)/css/details.css">
<!-- 加载ckplayer视频插件 -->
<script src="/assets/assets(home)/plugin/ckplayer/js/ckplayer.min.js"></script>

<!-- animate.css -->
<link rel="stylesheet" href="/assets/assets(home)/plugin/animate.min.css">

<!-- wowjs -->
<script src="/assets/assets(home)/plugin/wow.min.js"></script>

<!-- mescroll 上拉加载 下拉刷新 -->
<link rel="stylesheet" href="/assets/assets(home)/plugin/mescroll/mescroll.min.css">
<script src="/assets/assets(home)/plugin/mescroll/mescroll.min.js"></script>

<!-- 引入http请求插件 -->
<script src="/assets/assets(home)/plugin/axios/axios.min.js"></script>
<script src="/assets/assets(home)/plugin/axios/request.js"></script>

<script src="/assets/assets(home)/js/jquery-1.9.1.min.js"></script>
<script src="/assets/assets(home)/js/mui.min.js"></script>
<title>详情页</title>

<header class="mui-bar mui-bar-nav mui-bar-nav-bg">
    <!-- <a id="icon-menu" class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a> -->
    <div class="nav">
        <ul id="tab">
            <li class="active" data-type="course">课程</li>
            <li data-type="info">详情</li>
            <li data-type="comment">评论</li>
        </ul>
    </div>
</header>

<div id="tab-content">
    <!-- 课程 -->
    <div id="course" class="active">
        <div id="cover">
            <!-- 课程封面 -->
            <img class="cover_bg" src="{$subject.thumbs_text}">
            <!-- 中间播放键 -->
            <div id="play">
                <img src="/assets/assets(home)/images/play.png" />
            </div>
        </div>

        <!-- ckplayer视频容器元素 -->
        <div id="video"></div>

        <!-- 课程信息 -->
        <div class="head">
            <div class="info">
                <h4 class="name">{$subject.title}</h4>
                <div class="action">
                    {if condition="$subject.likes_active"}
                    <!-- 点赞 -->
                    <img class="thumbs" src="/assets/assets(home)/images/thumbs-up.png" alt="">
                    {else /}
                    <!-- 未点赞 -->
                    <img class="thumbs" src="/assets/assets(home)/images/thumbs.png" alt="">
                    {/if}
                    <span class="num">{$subject.likes_text}</span>
                </div>
            </div>
            <ul>
                <li>
                    <span>课程分类：</span>{$subject.category.name ? $subject.category.name : '暂无分类'}
                </li>
                <li>
                    <span>课程价格：</span>
                    <span class="price">￥{$subject.price}</span>
                </li>
                <li>
                    <span>章节总数：</span>{$chapter|count}
                </li>
                <li>
                    <span>发布时间：</span>{$subject.createtime_text}
                </li>
            </ul>
        </div>

        <!-- 授课老师 -->
        {if condition="$teacher"}
        <div class="teacher">
            <div class="title">授课老师</div>
            <div class="info">
                <div class="left">
                    <div class="avatar">
                        <a href="{:url('home/teacher/teacher_info',['teacherid' => $teacher['id']])}">
                            <img src="{$teacher.avatar_text}" alt="">
                        </a>
                    </div>
                </div>
                <div class="right">
                    <div class="name">
                        <a href="{:url('home/teacher/teacher_info',['teacherid' => $teacher['id']])}">
                            {$teacher.name}
                        </a>
                    </div>
                    <div class="job">{$teacher.job}</div>
                    <div class="content">
                        {$teacher.content ? $teacher.content : '这个人很懒什么都没写~'}
                    </div>
                </div>
            </div>
        </div>
        {/if}

        <!-- 课程章节 -->
        <div class="chapter">
            <div class="title">课程章节</div>
            <ul>
                {if condition="$chapter"}
                {foreach $chapter as $key=>$item}
                <li data-cid="{$item.id}" onclick="play(this)">{$key + 1}. {$item.title}</li>
                {/foreach}
                {else /}
                <li>暂无课程章节</li>
                {/if}
            </ul>
        </div>

        <!-- 购买 -->
        <div class="footer">
            <div class="footer-box">
                <div class="collection">
                    <!-- 收藏 -->
                    {if condition="$subject.collects_active"}
                    <img class="colthumbs" src="/assets/assets(home)/images/rate_active.png" alt="">
                    {else /}
                    <img class="colthumbs" src="/assets/assets(home)/images/rate.png" alt="">
                    {/if}

                </div>
                {if condition="$buy"}
                <a class="btn">已购买</a>
                {else /}
                <a href="{:url('home/search/confirm', ['subid' => $subject['id']])}" class="btn">购买</a>
                {/if}
            </div>
        </div>
    </div>

    <!-- 详情 -->
    <div id="info">
        <div class="mui-table-view content">{$subject.content}</div>
    </div>

    <!-- 评论 -->
    <div id="comment">
        <!-- 搜索框 -->
        <!-- <div class="search mui-input-row mui-search wow bounceIn">
            <input type="search" class="mui-input-clear" placeholder="请输入课程名称" name="search" />
        </div> -->

        <!-- 评论内容 -->
        <div id="list">
            <ul class="mui-table-view list"></ul>
        </div>
    </div>
</div>

<!-- 弹出菜单 -->
<div id="sheet1" class="mui-popover mui-popover-bottom mui-popover-action">
    <!-- 可选择菜单 -->
    <ul class="mui-table-view">
        <li class="mui-table-view-cell">
            <a id="buy" href="javascript:void(0)">
                立即购买
            </a>
        </li>
    </ul>
    <!-- 取消菜单 -->
    <ul class="mui-table-view">
        <li class="mui-table-view-cell">
            <a href="#sheet1"><b>取消</b></a>
        </li>
    </ul>
</div>

<script>
    // 章节ID
    var cid = 0
    var player = null

    //一进入到界面中，默认要拿到第一个的章节ID
    $(document).ready(function () {
        $(".chapter li:first").addClass('active')
        cid = $(".chapter li:first").data('cid')
        cid = cid ? cid : 0;
    })

    $('#tab li').click(function () {
        let type = $(this).data('type');

        $(this).addClass('active').siblings().removeClass('active');
        $('#tab-content #' + type).addClass('active').siblings().removeClass('active');
    })


    $("#iosActionsheetCancel").click(function () {
        mui('#sheet1').popover('toggle');
    })

    //点击章节
    function play(that) {
        $("#video").css('display', 'none')
        $("#cover").css('display', 'block')

        //暂停播放
        if (player) player.pause()


        //获取到章节ID
        cid = that.dataset.cid ? that.dataset.cid : 0

        $(that).addClass('active').siblings().removeClass('active')
    }

    // 点击播放
    $("#play").on('click', async () => {
        var result = await POST({
            url: `{:url('/search/play')}`,
            params: { cid }
        })

        if (result.code == 0) {
            mui.toast(result.msg)
            return false
        }

        var action = result.data.action ? result.data.action : '';

        if (action == 'buy') {
            // mui('#sheet1').popover('toggle');
            mui.toast(result.msg)
            return false;
        } else {
            //跳转容器结构
            $("#video").css('display', 'block')
            $("#cover").css('display', 'none')

            // 进行播放
            var videoObject = {
                container: '#video',
                video: result.data,
                autoplay: true,//是否自动播放
                loop: false,//是否需要循环播放
                ended: null,//结束显示的内容
                webFull: true,//是否启用页面全屏按钮，默认不启用
                theatre: true,//是否启用剧场模式按钮，默认不启用
                controls: true,//是否显示自带控制栏
                rightBar: true,//是否开启右边控制栏
                smallWindows: true,//是否启用小窗口模式
                smallWindowsDrag: true,//小窗口开启时是否可以拖动
                screenshot: true,//截图功能是否开启
                timeScheduleAdjust: 1,//是否可调节播放进度,0不启用，1是启用，2是只能前进（向右拖动），3是只能后退，4是只能前进但能回到第一次拖动时的位置，5是看过的地方可以随意拖动
                logo: '',//logo
            }

            player = new ckplayer(videoObject)
        }
    })

    // 立即购买
    $("#buy").on('click', function () {
        mui('#sheet1').popover('toggle');
        var btnArray = ['否', '是'];
        mui.confirm('请问您确认购买吗？', '尊敬的用户', btnArray, function (e) {
            if (e.index = 1) {
                location.href = "/assets/assets(home)/buy.html";
            }
        })
    })


    new WOW({
        boxClass: 'wow',      // 需要执行动画的元素的 class(默认是wow)
        animateClass: 'animated fadeInDown', // animation.css 动画的 class(默认是animated)
        offset: 0,          // 距离可视区域多少开始执行动画(默认为0)
        mobile: true,       // 是否在移动设备上执行动画(默认为true)
        live: true,       // 异步加载的内容是否有效(默认为true)
        scrollContainer: "#list" // 可选滚动容器选择器，否则使用窗口
    }).init();

    var keywords = '';
    var page = 0;       // 当前页
    var limit = 10;     // 每页查询多少条

    $("input[name=search]").change(function () {
        keywords = $(this).val()
        DownCallback()
    })

    // 配置下拉刷新和上拉加载
    var scroll = new MeScroll('list', {
        down: {
            auto: false, // 是否在初始化完毕之后自动执行下拉回调callback; 默认true
            callback: DownCallback // 下拉刷新的回调
        },
        up: {
            page: {
                num: page, // 当前页 默认0,回调之前会加1; 即callback(page)会从1开始
                size: limit // 每页数据条数,默认10
            },
            auto: true, // 是否在初始化时以上拉加载的方式自动加载第一页数据; 默认false
            isBounce: false, // 此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
            callback: UpCallback, // 上拉回调,此处可简写; 相当于 callback: function (page) { upCallback(page); }
            toTop: { //配置回到顶部按钮
                duration: 300,
                src: "/assets/assets(home)/plugin/mescroll/mescroll-totop.png", //默认滚动到1000px显示,可配置offset修改
                offset: 100,
                supportTap: true, //快速响应
            }
        }
    })


    // 下拉刷新回调
    function DownCallback() {
        scroll.resetUpScroll()
        $('#list .list').empty()
    }

    // 上拉刷新回调
    async function UpCallback(current) {
        //当前页码值
        page = current.num
        limit = current.size

        //组装数据
        var data = {
            page: page,
            limit: limit,
            keywords: keywords
        };

        var result = await POST({
            url: `/search/details?subid={$subject.id}`,
            params: data
        })

        if (!result) return false

        if (result.code == 0) {
            // mui.toast(result.msg, { duration: 1000 })
            // 暂无更多数据
            scroll.endBySize(0, 0)
            return false
        }

        var list = result.data.list
        var count = result.data.count

        //设置上拉加载状态
        scroll.endBySize(list.length, count)
        FetchList(list)
    }

    // 追加渲染数据
    function FetchList(list) {
        for (var item of list) {
            var rate = item.rate ? Math.abs(parseInt(item.rate)) : 0;
            var rate_temp = '';

            for (var i = 1; i <= 5; i++) {
                if (i <= rate) {
                    //红星
                    rate_temp += `<span><img src="/assets/assets(home)/images/rate_active.png" alt=""></span>`

                } else {
                    //灰星
                    rate_temp += `<span><img src="/assets/assets(home)/images/rate.png" alt=""></span>`
                }
            }

            var temp = `
                <li class="mui-table-view-cell mui-media wow bounceIn"  data-wow-delay="0.1s">
                    <img class="mui-media-object mui-pull-left userimg" src="${item.business.avatar_text}">
                    <div class="mui-media-body">
                        <div class="header">
                            <span class="nickname">${item.business.nickname}</span>
                        </div>
                        <p>${item.content}</p>
                        <div class="rate">${rate_temp}</div>
                    </div>
                </li>
            `
            $('#list .list').append(temp)
        }
    }


    //点赞的绑定事件
    $('.action').click(() => {
        //mui确认对话框
        mui.confirm(
            '是否确认点赞',
            '点赞提醒',
            ['取消', '确认'],
            async (res) => {
                if (res.index === 1) {
                    //发送请求
                    var result = await POST({
                        url: '/search/likes',
                        params: { subid: `{$subject.id}` }
                    })

                    // 关闭当前窗口
                    $('.mui-popup-backdrop').remove()
                    $('.mui-popup').remove()

                    //弹框信息
                    mui.toast(result.msg)

                    if (result.code) {
                        var action = result.data.action ? result.data.action : ''

                        //点赞动作
                        if (action == 'active') {
                            //换图片
                            $(".thumbs").prop('src', '/assets/assets(home)/images/thumbs-up.png')

                            //修改点赞数量
                            var num = $(".num").text()
                            num = parseInt(num) ? parseInt(num) : 0
                            $(".num").text(num + 1)
                        } else {
                            //换图片
                            $(".thumbs").prop('src', '/assets/assets(home)/images/thumbs.png')

                            //修改点赞数量
                            var num = $(".num").text()
                            num = parseInt(num) ? parseInt(num) : 0
                            $(".num").text(num - 1)
                        }
                    }
                }
            }
        )
    })

    //收藏的绑定事件
    $('.collection').click(() => {
        mui.confirm(
            '是否确认收藏',
            '收藏提醒',
            ['取消', '确认'],
            async (res) => {
                if (res.index === 1) {
                    //发送请求
                    var result = await POST({
                        url: '/search/collects',
                        params: { subid: `{$subject.id}` }
                    })

                    // 关闭当前窗口
                    $('.mui-popup-backdrop').remove()
                    $('.mui-popup').remove()

                    //弹框信息
                    mui.toast(result.msg)

                    if (result.code) {
                        var action = result.data.action ? result.data.action : ''

                        //点赞动作
                        if (action == 'active') {
                            //换图片
                            $(".colthumbs").prop('src', '/assets/assets(home)/images/rate_active.png')
                        } else {
                            //换图片
                            $(".colthumbs").prop('src', '/assets/assets(home)/images/rate.png')
                        }
                    }
                }
            }
        )
    })

</script>